package com.huateng.util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;

/**
 * Created by joy on 2016/11/7.
 */
@Component
public class SecureUtils {
    private static Logger logger = Logger.getLogger(SecureUtils.class);

    private  Configuration conf = null;

    @Value("${secure.option}")
    private String secure;
    @Value("${cluster}")
    private String cluster;
    @Value("${kerberos.username}")
    private String principal;
    @Value("${kerberos.keytab}")
    private String keytabFilename;
    @Value("${kerberos.krbconf}")
    private String krbconf;


    private static String JAVA_SECURITY_KRB5_CONF = "java.security.krb5.conf";
    private static String ZOOKEEPER_AUTH_PRINCIPAL = "zookeeper.server.principal";
    private static String JAVA_SECURITY_LOGIN_CONF = "java.security.auth.login.config";

    public  void login() throws Exception{
        String basePath = System.getProperty("user.dir") + File.separator + cluster + File.separator;
        String userPrincipal = principal;
        String userKeytabPath = basePath + "user.keytab";
        String krb5ConfPath = basePath + "krb5.conf";
        String jassFilePath = basePath + "jaas.conf";
        System.setProperty(JAVA_SECURITY_KRB5_CONF, krb5ConfPath);
        System.setProperty(JAVA_SECURITY_LOGIN_CONF, jassFilePath);
        System.setProperty(ZOOKEEPER_AUTH_PRINCIPAL, "zookeeper/hadoop.hadoop.com");
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab(userPrincipal, userKeytabPath);
    }

    @PostConstruct
    public  void init(){
        initConf();
        if("kerberos".equals(secure)){
            try {
                login();
            } catch (Exception e) {
                e.printStackTrace();
                logger.equals(e);
            }
        }
    }


    private void initConf(){
        conf = new Configuration();
        String userdir = System.getProperty("user.dir") + File.separator + cluster + File.separator;
        conf.addResource(new Path(userdir + "core-site.xml"));
        conf.addResource(new Path(userdir + "hdfs-site.xml"));
        conf.addResource(new Path(userdir + "hbase-site.xml"));
    }


    public Configuration getConf() {
        return conf;
    }
}
